// api/auth-manager.ts - 优化后的认证管理系统
import type { 
  User, 
  LoginResponse,
  AuthStateChangeListener
} from '../types/index';
import { STORAGE_KEYS, HTTP_CONFIG } from '../config/http';

/** 认证状态 */
export enum AuthState {
  UNAUTHENTICATED = 'unauthenticated',
  AUTHENTICATED = 'authenticated',
  TOKEN_EXPIRING = 'token_expiring',
  TOKEN_EXPIRED = 'token_expired',
  INACTIVE_EXPIRED = 'inactive_expired',
}

/** 简化的认证管理器 */
class AuthManager {
  private currentUser: User | null = null;
  private currentToken: string | null = null;
  private listeners: Set<AuthStateChangeListener> = new Set();
  private refreshPromise: Promise<string> | null = null;
  
  constructor() {
    this.init();
  }

  /** 初始化 - 恢复登录状态 */
  private init(): void {
    try {
      const token = wx.getStorageSync(STORAGE_KEYS.TOKEN);
      const userInfo = wx.getStorageSync(STORAGE_KEYS.USER_INFO);
      
      if (token && userInfo && this.isValidAuth(token)) {
        this.currentToken = token;
        this.currentUser = userInfo;
        this.updateLastActiveTime(); // 重置活跃时间
        console.log('[AuthManager] 登录状态已恢复');
      } else {
        this.clearAuthState();
      }
    } catch (error) {
      console.error('[AuthManager] 初始化失败:', error);
      this.clearAuthState();
    }
  }

  /** 验证认证信息有效性 */
  private isValidAuth(token: string): boolean {
    // 检查Token格式
    if (!token || typeof token !== 'string') return false;
    
    // 检查不活跃过期（30天）
    const lastActive = wx.getStorageSync(STORAGE_KEYS.LAST_ACTIVE);
    if (lastActive) {
      const elapsed = Date.now() - Number(lastActive);
      if (elapsed > HTTP_CONFIG.INACTIVITY_EXPIRE_TIME) {
        console.log('[AuthManager] 不活跃时间过长，需要重新登录');
        return false;
      }
    }
    
    return true;
  }

  /** 登录 */
  async login(loginResponse: LoginResponse): Promise<void> {
    try {
      const { user, token } = loginResponse;
      
      if (!user || !token?.token) {
        throw new Error('登录响应数据无效');
      }

      // 保存认证信息
      this.currentToken = token.token;
      this.currentUser = user;
      
      // 持久化存储
      wx.setStorageSync(STORAGE_KEYS.TOKEN, token.token);
      wx.setStorageSync(STORAGE_KEYS.USER_INFO, user);
      wx.setStorageSync(STORAGE_KEYS.LOGIN_TIME, Date.now());
      this.updateLastActiveTime();
      
      // 兼容旧代码的存储
      wx.setStorageSync('userInfo', user);
      wx.setStorageSync('userId', user.id);
      wx.setStorageSync('userName', user.nickname || user.username);
      wx.setStorageSync('token', token.token);
      wx.setStorageSync('isLoggedIn', true);
      wx.removeStorageSync('isGuestMode');
      
      // 通知监听器
      this.notifyAuthStateChange(true, user);
      
      console.log('[AuthManager] 登录成功:', user.username);
    } catch (error) {
      console.error('[AuthManager] 登录失败:', error);
      throw error;
    }
  }

  /** 登出 */
  async logout(): Promise<void> {
    this.clearAuthState();
    this.notifyAuthStateChange(false);
    console.log('[AuthManager] 已登出');
  }

  /** 刷新Token */
  async refreshToken(httpClient?: any): Promise<string> {
    if (this.refreshPromise) {
      return this.refreshPromise;
    }
    
    this.refreshPromise = this.performTokenRefresh(httpClient);
    
    try {
      const newToken = await this.refreshPromise;
      return newToken;
    } finally {
      this.refreshPromise = null;
    }
  }

  /** 执行Token刷新 */
  private async performTokenRefresh(httpClient?: any): Promise<string> {
    try {
      if (!httpClient) {
        // 使用简单的wx.request，避免循环依赖
        throw new Error('HTTP客户端未提供');
      }
      
      const response = await httpClient.get('/api/auth/refresh-token', null, {
        skipTokenRefresh: true,
        showError: false,
        headers: { 'Authorization': `Bearer ${this.currentToken}` }
      });
      
      if (!response?.data?.data?.token) {
        throw new Error('刷新响应无效');
      }
      
      const newToken = response.data.data.token;
      
      // 更新Token
      this.currentToken = newToken;
      wx.setStorageSync(STORAGE_KEYS.TOKEN, newToken);
      wx.setStorageSync('token', newToken); // 兼容
      
      return newToken;
    } catch (error) {
      // 刷新失败，清除状态
      this.clearAuthState();
      this.notifyAuthStateChange(false);
      throw error;
    }
  }

  /** 更新最后活跃时间 */
  updateLastActiveTime(): void {
    const now = Date.now();
    wx.setStorageSync(STORAGE_KEYS.LAST_ACTIVE, now);
  }

  /** 更新Token */
  async updateToken(newToken: string): Promise<void> {
    try {
      this.currentToken = newToken;
      wx.setStorageSync(STORAGE_KEYS.TOKEN, newToken);
      
      // 同时更新活跃时间
      this.updateLastActiveTime();
      
      console.log('[AuthManager] Token已更新');
    } catch (error) {
      console.error('[AuthManager] 更新Token失败:', error);
      throw error;
    }
  }

  /** 检查是否已登录 */
  isAuthenticated(): boolean {
    return !!(this.currentToken && this.currentUser);
  }

  /** 检查是否不活跃过期 */
  isInactivityExpired(): boolean {
    try {
      const lastActive = wx.getStorageSync(STORAGE_KEYS.LAST_ACTIVE);
      if (!lastActive) return false;
      
      const elapsed = Date.now() - Number(lastActive);
      return elapsed > HTTP_CONFIG.INACTIVITY_EXPIRE_TIME;
    } catch (error) {
      return false;
    }
  }



  /** 获取当前Token */
  getToken(): string | null {
    return this.currentToken;
  }

  /** 获取当前用户 */
  getCurrentUser(): User | null {
    return this.currentUser;
  }

  /** 获取认证状态 */
  getAuthState(): AuthState {
    if (!this.isAuthenticated()) {
      return AuthState.UNAUTHENTICATED;
    }
    
    if (this.isInactivityExpired()) {
      return AuthState.INACTIVE_EXPIRED;
    }
    
    return AuthState.AUTHENTICATED;
  }

  /** 添加状态监听器 */
  addAuthStateListener(listener: AuthStateChangeListener): () => void {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  }

  /** 清除认证状态 */
  private clearAuthState(): void {
    this.currentToken = null;
    this.currentUser = null;
    
    // 清除所有相关存储
    const keysToRemove = [
      STORAGE_KEYS.TOKEN,
      STORAGE_KEYS.USER_INFO,
      STORAGE_KEYS.LOGIN_TIME,

      STORAGE_KEYS.LAST_ACTIVE,
      // 兼容旧代码的key
      'userInfo', 'userId', 'userName', 'token', 'isLoggedIn'
    ];
    
    keysToRemove.forEach(key => {
      try {
        wx.removeStorageSync(key);
      } catch (error) {
        console.warn(`清除存储失败: ${key}`, error);
      }
    });
  }

  /** 通知状态变更 */
  private notifyAuthStateChange(isLoggedIn: boolean, user?: User): void {
    this.listeners.forEach(listener => {
      try {
        listener(isLoggedIn, user);
      } catch (error) {
        console.error('[AuthManager] 监听器执行失败:', error);
      }
    });
  }
}

// 创建全局实例
export const authManager = new AuthManager();
export default authManager;
